package com.ripplezjw.blog.Service;

import com.ripplezjw.blog.mapper.UserMapper;
import com.ripplezjw.blog.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User loginUser(String username, String password) {
//        System.out.println(username + password);
        return userMapper.findUserByUserNameAndPassWord(username, password);
    }

    public int registerUser(String username, String password) {
//        System.out.println(username + password);
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) return -1;
        if (userMapper.cntUsername(username) > 0) return -1;
        return userMapper.addUser(username, password);
    }

    public String addUser(User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty((user.getPassword()))) return "用户名或密码不能为空";
        if (userMapper.cntUsername(user.getUsername()) > 0) return "用户名已存在";
        userMapper.addUser(user.getUsername(), user.getPassword());
        return "";
    }

    public List<User> showAllUsers() {
        return userMapper.findUsers();
    }

    public void clickDelUserBtn(int userId) {
        userMapper.delUserByUserId(userId);
    }

    public User clickModUserBtn(int userId) {
        return userMapper.findUserById(userId);
    }

    public String modUser(User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty((user.getPassword()))) return "用户名或密码不能为空";
        if (!userMapper.findUserById(user.getUserId()).getUsername().equals(user.getUsername())
                && userMapper.cntUsername(user.getUsername()) > 0) return "用户名已存在";

        userMapper.updateUserByUserId(user);
        return "";
    }
}
